package com.stu.exercise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.stu.exercise.entity.R;
import com.stu.exercise.entity.User;
import com.stu.exercise.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public R<List<User>> list(){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User.class, info -> !info.getColumn().equals("password"));
        List<User> list = userService.list(wrapper);
        return R.success(list);
    }

    @RequestMapping("/add")
    public R add(@RequestBody User user){
        boolean save = userService.save(user);
        if (save){
            return R.success("添加成功", null);
        }
        return R.error(500,  "添加失败");
    }
    
    @RequestMapping("/edit")
    public R edit(@RequestBody User user){
        boolean update = userService.updateById(user);
        if (update){
            return R.success("修改成功", null);
        }
        return R.error(500,  "修改失败");
    }

    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable Integer id){
        boolean remove = userService.removeById(id);
        if (remove){
            return R.success("删除成功", null);
        }
        return R.error(500,  "删除失败");
    }

    @RequestMapping("/change")
    public R edit(@RequestBody Map<String, Object> map){
        Integer id = (Integer) map.get("id");
        Integer status = (Integer) map.get("status");
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getStatus, status).eq(User::getId, id);
        boolean update = userService.update(wrapper);
        if (update){
            return R.success("修改成功", null);
        }
        return R.error(500,  "修改失败");
    }

}
